package com.yd.mvc.baseController.interceptor;

import com.yd.mvc.baseController.util.AuthUtil;
import com.yd.mvc.baseController.util.CurrentIP;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;


public class CookieInterceptor implements HandlerInterceptor {
	
	private static final ThreadLocal<Cookie> theCookie = new ThreadLocal<Cookie>();
	
/*
	@Autowired
	private OnlineUtils ou;
*/
	
	private String[] urls;

	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		MDC.put("nodeId", System.getProperty("nodeId"));//向log4j中记录节点id
		CurrentIP.putIP(request);
		Cookie ck = WebUtils.getCookie(request, AuthUtil.getCookieName());
		if(ck==null){
			ck = new Cookie(AuthUtil.getCookieName(), String.format("0%s", UUID.randomUUID().toString()));
			ck.setPath(AuthUtil.getCookiePath());
			//ck.setDomain(AuthUtil.getCookieDomain());
			ck.setMaxAge((int) AuthUtil.getExpierinterval()/1000);
			response.addCookie(ck);
		}
		theCookie.set(ck);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		/*AuthedUser au = AuthUtil.getCurrentUser();
		String url = request.getRequestURI();
		//FIXME 应当有白名单或者黑名单,以便判断哪些地址记录或者不记录
		if(au==null){
			ou.broadcast(theCookie.get().getValue().substring(1), url);//未登录用户记录
		}else{
			ou.broadcast(au.getUserId(), url);//登录用户记录
		}*/
		theCookie.remove();
	}	

}
